package com.yntx.usercenter.authentication.util;

import com.yntx.usercenter.common.config.TenantUserContextHolder;
import com.yntx.usercenter.common.constants.SecurityConstant;
import com.yntx.usercenter.common.constants.StringPool;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Description: HTTP请求工具类
 *
 * @author Liziba
 * @version 1.0
 * @date 2022/12/20 2:29 PM
 * @since JDK 1.8
 */
@Slf4j
public class HttpRequestUtil {

    public static TenantUserContextHolder getTenantUserContextHolder(HttpServletRequest request) {
        return TenantUserContextHolder.builder()
                .ip(ipResolve(request))
                .tenantId(request.getHeader(SecurityConstant.YNTX_TENANT_ID))
                .isShareUser(Boolean.valueOf(request.getHeader(SecurityConstant.YNTX_SHARE_USER)))
                .systemId(request.getHeader(SecurityConstant.YNTX_SYSTEM_ID))
                .systemCode(request.getHeader(SecurityConstant.YNTX_SYSTEM_CODE))
                .token(request.getHeader(SecurityConstant.HEADERS_TOKEN))
                // todo:柔性降级，从token中直接解析用户名-在网关做
                .userId(request.getHeader(SecurityConstant.YNTX_USER_ID))
                .username(request.getHeader(SecurityConstant.YNTX_USERNAME))
                .build();
    }

    /**
     * IP地址解析
     *
     * @param request
     * @return
     */
    public static String ipResolve(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || StringPool.UNKNOWN.equals(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || StringPool.UNKNOWN.equals(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || StringPool.UNKNOWN.equals(ip)) {
            ip = request.getRemoteAddr();
        }
        String comma = StringPool.COMMA;
        if (ip.contains(comma)) {
            ip = ip.split(comma)[0];
        }
        if (StringPool.LOCALHOST.equals(ip)) {
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                log.error(e.getMessage(), e);
            }
        }
        return ip;
    }

}
